package eclMain;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

public class EveChatManager {

	public EveChatManager(Path logPath) {
		FileManager fm = null;
		try {
			fm = new FileManager(logPath); //file manager gets the recent files, and starts a thread to watch for new ones
		} catch (Exception e) {
			System.err.print("Unable to Open Directory");
			e.printStackTrace();
		}
		readFiles(fm); //start reading out new chat lines as they come in
	}
	
	public void readFiles(final FileManager manager) {
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				ArrayList<ChatFile> masterList = FileManager.getMasterList(); //list of files to be checked
				BucketList buckets = new BucketList(5);
				
				while (true) {
					long start = System.currentTimeMillis();
					
					//update the master list
					masterList = FileManager.getMasterList();
					
					//start reading new lines from all files
					ArrayList<ChatLine> newLines = new ArrayList<ChatLine>();
					for (ChatFile file : masterList) { //collect new lines from all files
						ArrayList<ChatLine> temp = null;
						try {
							temp = file.readAvailable(-1); //attempt to get new chat lines
//							for (ChatLine line : temp) System.out.println(line); //debug only. Look here if I'm not getting anything to the notifier for some reason
						} catch (Exception e) {
							Notifier.errorNotify("Unable to read from file: " + file.toString());
							manager.removeFileFromList(file);
						}
						if (temp != null) newLines.addAll(temp);
					}
					
					ArrayList<ChatLine> cleanedLines = buckets.removeDuplicates(newLines); //remove duplicate lines both from this list, and from the last few seconds/cycles
					
					//XXX: at this point, shove the lines to some other program (finally!!)
//					for (ChatLine line : cleanedLines) System.out.println(line);
					Notifier.notifyOfNewChat(cleanedLines);
					
					//I want to make sure that I'm reading the new lines in once every second. If for some reason I'm taking longer than a second to read and process, start the next read immediately.
					long difference = System.currentTimeMillis() - start;
					if (difference >= 1000) continue;
					else {
						try {
							Thread.sleep(1000 - difference); //otherwise, wait until a full second has passed since I started this loop
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				} //end while true
			}
		});
		thread.start();
	}
	
	public static void main(String[] args) {
		Path logPath = Paths.get(System.getProperty("user.home"), "Documents", "EVE", "logs", "Chatlogs"); //standard chatlog path
//		Path logPath = Paths.get(System.getProperty("user.home"), "Documents", "EVE", "logs", "Testlogs"); //Test path for test chatlogs
		new EveChatManager(logPath);
	}
}
